package com.cn.web.app.order.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.config.OrderConfig;
import com.cn.exception.MyException;
import com.cn.global.GlobalParamters;
import com.cn.global.GlobalParamtersUtil;
import com.cn.page.PageVo;
import com.cn.upload.config.UploadConfig;
import com.cn.user.UserDO;
import com.cn.util.DateUtil;
import com.cn.util.SnowflakeIdWorkerUtil;
import com.cn.web.app.baidu.BaiDuSdk;
import com.cn.web.app.order.entity.OrderInfoEntity;
import com.cn.web.app.order.mapper.IOrderInfoMapper;
import com.cn.web.app.order.vo.OrderInfoListVO;
import com.cn.web.app.order.vo.OrderInfoSearch;
import com.cn.web.app.template.entity.OrderTemplateEntity;
import com.cn.web.app.template.service.OrderTemplateService;
import com.cn.web.app.template.vo.OrderTemplateListVO;
import com.cn.web.app.template.vo.OrderTemplateSearch;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * description: OrderInfoService <br>
 * date: 24.7.12 11:56 <br>
 * author: cn_yaojin <br>
 * version: 1.0 <br>
 */
@Service
@Slf4j
public class OrderInfoService {

    @Autowired
    private IOrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderTemplateService orderTemplateService;

    @Autowired
    private BaiDuSdk baiDuSdk;

    @Autowired
    private UploadConfig uploadConfig;

    @Autowired
    private OrderConfig orderConfig;

    private ExecutorService executorService = Executors.newFixedThreadPool(4);


    public void edit(OrderInfoEntity info, UserDO token) {
        if (info.getId() == null || info.getId() <= 0) {
            info.setId(SnowflakeIdWorkerUtil.getId());
            info.setAddTime(DateUtil.getTime());
            info.setUserId(token.getId().toString());
            info.setOrgId(token.getOrgs().get(0).getId().toString());
            this.orderInfoMapper.insert(info);
        } else {
            info.setUpdateTime(DateUtil.getTime());
            this.orderInfoMapper.updateById(info);
        }

        try {
            iocrRecognise(info);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public OrderInfoEntity find(String id) {
        return this.orderInfoMapper.selectById(id);
    }

    public OrderInfoListVO findVO(String id) {
        QueryWrapper<OrderInfoSearch> query = new QueryWrapper<>();
        query.eq("o1.id", id);
        List<OrderInfoListVO> items = this.orderInfoMapper.list(query);
        if (items != null && items.size() > 0) {
            return items.get(0);
        }
        return null;
    }

    public void del(String id) {
        this.orderInfoMapper.deleteById(id);
    }

    public List<OrderInfoListVO> list(OrderInfoSearch search) {
        QueryWrapper<OrderInfoSearch> query = new QueryWrapper<>();
        query.eq("1", 1);
        if (search != null) {
            if (search.getType() != null) {
                if (search.getType() == 1) {
                    //用户查询自己的
                    query.eq("o1.user_id", search.getUserId());
                } else if (search.getType() == 2) {
                    //组织机构查询本机构
                    query.eq("o1.org_id", search.getOrgId());
                }
            }
            if (search.getStatus() != null) {
                query.eq("o1.status", search.getStatus());
            }
            if (StringUtils.isNotEmpty(search.getStart())) {
                query.ge("o1.add_time", search.getStart());
            }
            if (StringUtils.isNotEmpty(search.getStop())) {
                query.le("o1.add_time", search.getStop());
            }
            if (StringUtils.isNotEmpty(search.getSearch())) {
                query.eq("o1.id", search.getSearch());
            }
        }
        List<OrderInfoListVO> data = this.orderInfoMapper.list(query);
        return data;
    }

    public PageInfo<OrderInfoListVO> page(PageVo<OrderInfoSearch> pageVo) {
        return PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize()).doSelectPageInfo(() -> {
            list(pageVo.getParam());
        });
    }

    public void iocrRecognise(OrderInfoEntity info) {
        OrderTemplateEntity template = this.orderTemplateService.find(info.getTemplateId());
        if (template != null) {
            if (StringUtils.isEmpty(template.getBaiduTemplateId())) {
                throw new MyException("CID不存在");
            }

            String dataDir = this.uploadConfig.getLocalUploadConfig().getDataDir();
            String filePath = dataDir + info.getOrderUrl();
            GlobalParamters globalParamters = GlobalParamtersUtil.get();
            String urlPath = globalParamters.getFileDomain() + info.getOrderUrl();
            String destPath = dataDir + info.getId() + ".jpg";
            HttpUtil.downloadFileFromUrl(urlPath, destPath);
            File file = new File(destPath);
            String base64Str = Base64.encode(file);
            String url = this.orderConfig.getApiDomain() + "/ocr";

//            String base64 = Base64.encode(new File(filePath));
//            System.out.println(base64);
            Map<String, Object> params = new java.util.HashMap<>();
            params.put("code", base64Str);
            params.put("cid", template.getBaiduTemplateId());
            String result = HttpUtil.post(url, JSON.toJSONString(params));
            log.error(result);
            JSONObject json = JSON.parseObject(result);
            int code = json.getInteger("code");
            if (code == 200) {
                info.setIdentifyContent(result);
                info.setStatus(1);
                this.orderInfoMapper.updateById(info);
            } else {
                info.setStatus(2).setRemark("识别失败");
                this.orderInfoMapper.updateById(info);
                throw new MyException("识别失败");
            }
        }
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void handleTask() {
        QueryWrapper<OrderInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        List<OrderInfoEntity> list = this.orderInfoMapper.selectList(queryWrapper);
        for (OrderInfoEntity item : list) {
            iocrRecognise(item);
        }
    }

    public static void main(String[] args) {
        String url = "http://rec1.xtgss.cn/ocr";
        String templateId = "0b027fb7260cf1837e0d4f6c9e361217";
        String filePath = "/data/票据1.png";
        String base64 = Base64.encode(new File(filePath));
        System.out.println(base64);
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("code", base64);
        params.put("cid", templateId);
//        String result = "{\"code\":200,\"message\":null,\"data\":[{\"付款人账号\":\"621060188013000239477\"},{\"开户行名称\":\"招商银行股份有限公司兰州城南支行\"},{\"收款人账号\":\"6214839325200293\"},{\"收款人名称\":\"姚进\"},{\"付款人名称\":\"兰州微宝宝信息技术有限责任公司\"},{\"回单编号\":\"413555725681\"},{\"金额\":\"657.90\"}]}\n";
        String result = HttpUtil.post(url, JSON.toJSONString(params));
//        String result = HttpUtil.post(url, params);
        System.out.println(result);
        JSONObject json = JSON.parseObject(result);
        int code = json.getInteger("code");
        if (code == 200) {
            System.out.println(json.getString("data"));
            Map<String, Object> map = JSON.parseObject(json.getString("data"), Map.class);
            map.forEach((k, v) -> {
                System.out.println(k + ":" + v);
            });
        } else {
            throw new MyException("识别失败");
        }

    }


}
